package com.ttmusic.fragments.maintab;

import java.util.List;

import com.ttmusic.activitys.MainActivity;
import com.ttmusic.activitys.R;
import com.ttmusic.dao.MusicListDao;
import com.ttmusic.entity.MusicList;
import com.ttmusic.utils.Utils;
import com.ttmusic.view.adapters.MusicListAdapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MusicListFragment extends ListFragment{
	
	private Context mContext;
	private MusicListDao musicListDao;
	private LayoutInflater inflater;
	private View view;
	private ListView listview_musiclist;
	private MusicListAdapter musicListAdapter;
	private List<MusicList> musicLists;
	
	public MusicListFragment(Context mContext) {
		this.mContext = mContext;
		this.musicListDao = MusicListDao.getInstance();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.inflater = inflater;
		view = inflater.inflate(R.layout.fragment_musiclist, container, false);
		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		listview_musiclist = this.getListView();
		musicLists = musicListDao.findAll();
		musicListAdapter = new MusicListAdapter(mContext, musicLists, true);
		listview_musiclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long index) {
				MusicList ml = musicLists.get((int)index);
				//Toast.makeText(mContext, "listid->"+ml.getListId()+"->"+ml.getListName(), Toast.LENGTH_LONG).show();
				if("我的最爱".equals(ml.getListName())) {
					MainActivity.radio_mylove.setChecked(true);
				}
				//切换到“我的最爱”fragment
				if(null == MainActivity.musicOfListFragment)
					MainActivity.musicOfListFragment = new MusicOfListFragment(MusicListFragment.this.getContext(), ml);
				else
					MainActivity.musicOfListFragment.setMusicList(ml);
				Utils.go(MusicListFragment.this.getActivity().getSupportFragmentManager(), MainActivity.current, MainActivity.musicOfListFragment, R.id.framecontent);
			}
		});
		listview_musiclist.setAdapter(musicListAdapter);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if(!hidden) {
			musicLists = musicListDao.findAll();
			musicListAdapter.setMusicLists(musicLists);
			musicListAdapter.notifyDataSetChanged();
		}
		super.onHiddenChanged(hidden);
	}

}
